package com.gouda.core.dao;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gouda.core.entity.UseDistrictEntity;
import com.gouda.core.enums.GeneralStateEnum;
import com.gouda.core.utils.CacheKey;
import com.hephaestus.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.amethyst.atlas.db.MagicDao;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by souu on 15/12/5.
 */
@Slf4j
@Repository
public class UseDistrictDao extends MagicDao {

    private static final String BASE_SQL = "select id,city_id,district_name,lon,lat,state,create_time from use_district";

    private static final String BASE_SQL_ID = "select id from use_district";

    public List<UseDistrictEntity> getUseDistrictByCity(long cityId) {
        if (cityId <= 0) {
            return null;
        }
        List<Long> ids = (List<Long>) CacheUtil.getInstance().get(CacheKey.getUseDistrictByCity(cityId));
        if (ids == null || ids.isEmpty()) {
            StringBuilder sql = new StringBuilder("");
            sql.append(BASE_SQL_ID);
            sql.append(" where city_id = :cityId");
            sql.append(" and state = :state");
            Map<String, Object> param = Maps.newHashMap();
            param.put("cityId", cityId);
            param.put("state", GeneralStateEnum.YES.getCode());
            ids = super.listColumns(UseDistrictEntity.class, sql.toString(), param, Long.class);
            if (ids == null || ids.isEmpty()) {
                return null;
            }
            try {
                CacheUtil.getInstance().add(CacheKey.getUseDistrictByCity(cityId), ids);
            } catch (InterruptedException e) {
                log.error("getUseDistrictByCity cache error:{}", e.getMessage());
            }
        }
        List<UseDistrictEntity> entities = Lists.newArrayList();
        for (Long id : ids) {
            UseDistrictEntity entity = this.unique(UseDistrictEntity.class, id);
            if (entity != null) {
                entities.add(entity);
            }
        }

        return entities;
    }


    public boolean insert(final UseDistrictEntity entity) {
        boolean bool = super.insert(entity);
        if (bool) {
            try {
                CacheUtil.getInstance().delete(CacheKey.getUseDistrictByCity(entity.getCityId()));
            } catch (InterruptedException e) {
                log.error("UseDistrictInsert cache error:{}", e.getMessage());
            }
        }
        return bool;
    }


    public boolean update(final UseDistrictEntity entity) {
        boolean bool = super.update(entity);
        if (bool) {
            try {
                CacheUtil.getInstance().delete(CacheKey.getUseDistrictByCity(entity.getCityId()));
            } catch (InterruptedException e) {
                log.error("UseDistrictUpdate cache error:{}", e.getMessage());
            }
        }
        return bool;
    }
}
